const puppeteer = require('puppeteer');
const fs = require("fs");

module.exports = {
  createScoreImgBase64: function (rankList, groupTitle, matchTitle, createTime, themeOption, bottomText){
    const sf = this;
    return (async () => {
      let html = fs.readFileSync("template.html", {encoding: "utf-8"});
      let tbodyHtml = sf.getTbodyHtml(rankList);
      let defaultTheme = {
        red: "#d03054",
        blue: "#1890ff", 
        cyan: "#07b198",
        pink: "#ee4998",
        orange: "#f26504",
        purple: "#8965d7",
        green: "#80aa7a",
        black: "#222222",
        darkblue:"#286090",
      };
      bottomText = bottomText || "快乐打字，积极向上。更多排行：https://www.dazi.club/";
      themeOption = themeOption || {};
      themeOption.type = themeOption.type || 1;
      themeOption.background = themeOption.background || '#d03054';
      if(defaultTheme[themeOption.background]){
        themeOption.background = defaultTheme[themeOption.background];
      }

      html = html.replace(new RegExp("\\{\\{GROUP_TITLE\\}\\}", "g"), groupTitle);
      html = html.replace(new RegExp("\\{\\{MATCH_TITLE\\}\\}", "g"), matchTitle);
      html = html.replace(new RegExp("\\{\\{CREATE_TIME\\}\\}", "g"), createTime);
      html = html.replace(new RegExp("\\{\\{BOTTOM_TEXT\\}\\}", "g"), bottomText);
      html = html.replace(new RegExp("\\/\\*background:\\{\\{TOP_BACKGROUND\\}\\};\\*\\/", "g"), "background:"+themeOption.background+";");
      html = html.replace(new RegExp("\\{\\{TBODY_HTML\\}\\}", "g"), tbodyHtml);
      const browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] });
      const page = await browser.newPage();
      await page.setViewport({
        width: 774,
        height: 220 + rankList.length * 38,
        deviceScaleFactor: 1.5,
      });
      await page.setContent(html);
      let imgBase64 = await page.screenshot({
        type: "jpeg",
        encoding: "base64",
        quality: 100,
      });
      await browser.close();
      return imgBase64;
    })();
  },
  
  getTbodyHtml: function (rankList){
    let keys = ["ranking", "username", "speed", "keystrokes", "ma_chang", "hui_gai", "wrong_number", "input_method"];
    let tbodyHtml = "";
    rankList.forEach((item, index)=>{
        let arr = keys.map(sitem=>{return "<td>" + (item[sitem]) +  "</td>"});
        tbodyHtml += `<tr>${arr.join("")}</tr>`;
    });
    return tbodyHtml;
  }
  
}
